package com.zou.controller.backstage;

import com.zou.commons.constants.Constants;
import com.zou.commons.domain.ReturnObject;
import com.zou.pojo.SysUser;
import com.zou.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping({"/login", "/backstage/login"})
    public String login() {
        return "backstage/login";
    }

    @PostMapping("/backstage/login")
    public @ResponseBody
    Object login(String username, String password, String captcha, String isRemember,
                 HttpServletResponse response, HttpSession session) {
        ReturnObject returnObject = new ReturnObject();
        if (!captcha.equals(session.getAttribute("captcha").toString())) {
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("验证码错误");
        } else {
            returnObject = sysUserService.sysUserLogin(username, password);
            if (returnObject.getCode() == Constants.RETURN_OBJECT_CODE_SUCCESS) {
                // 登录成功，把用户保存到session中
                SysUser sysUser = (SysUser) returnObject.getOther();
                session.setAttribute(Constants.SESSION_USER, sysUser);
                //如果需要记住密码，则往外写cookie
                if ("true".equals(isRemember)) {
                    editLoginCookie(response, sysUser.getUsername(), sysUser.getPassword(), 10 * 24 * 60 * 60);
                } else {
                    //把没有过期cookie删除
                    editLoginCookie(response, "0", "0", 0);
                }
            }
        }
        return returnObject;
    }

    @GetMapping("/backstage/logout")
    public String logout(HttpServletResponse response, HttpSession session) {
        editLoginCookie(response, "1", "1", 0);
        //销毁session
        session.invalidate();
        return "redirect:login";
    }

    /**
     * 修改cookie
     *
     * @param response
     * @param loginName
     * @param loginPwd
     * @param maxAge
     */
    private void editLoginCookie(HttpServletResponse response, String loginName, String loginPwd, int maxAge) {
        Cookie c1 = new Cookie("loginName", loginName);
        c1.setMaxAge(maxAge);
        response.addCookie(c1);
        Cookie c2 = new Cookie("loginPwd", loginPwd);
        c2.setMaxAge(maxAge);
        response.addCookie(c2);
    }
}
